import React, { createContext, useState, useEffect, ReactNode } from 'react'

type SidebarContextType = {
  isCollapsed: boolean
  toggleSidebar: () => void
}

export const SidebarContext = createContext<SidebarContextType>({
  isCollapsed: false,
  toggleSidebar: () => {},
})

type SidebarProviderProps = {
  children: ReactNode
}

export const SidebarProvider: React.FC<SidebarProviderProps> = ({
  children,
}) => {
  const [isCollapsed, setIsCollapsed] = useState<boolean>(false)

  useEffect(() => {
    // 检查本地存储中的侧边栏状态
    const sidebarState = localStorage.getItem('sidebarState') || 'expanded'
    setIsCollapsed(sidebarState === 'collapsed')
  }, [])

  const toggleSidebar = () => {
    const newIsCollapsed = !isCollapsed
    setIsCollapsed(newIsCollapsed)
    localStorage.setItem(
      'sidebarState',
      newIsCollapsed ? 'collapsed' : 'expanded'
    )
  }

  return (
    <SidebarContext.Provider value={{ isCollapsed, toggleSidebar }}>
      {children}
    </SidebarContext.Provider>
  )
}
